﻿/* 
 * BtCommLib - the OpenWebNet .NET Library
 *
 * Copyright (C) 2011 BTicino S.p.A.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BTicino.BtCommLib.Domain.LowLevel;
using BTicino.BtCommLib.Domain.Util;
using BTicino.BtCommLib.Communication;
using System.Reflection;
using BTicino.BtCommLib.Trace;


namespace BTicino.BtCommLib.Handlers
{
    public class BTOpenEventHandler
    {

        #region Data members

        private BTOpenConverter conv = new BTOpenConverter();
        private BTOpenProtocolAdapter opa = new BTOpenProtocolAdapter();
        private static BTLibLogger logger = BTLibLogger.createLogger("BTOpenEventHandler");

        #endregion

        #region Constructor

        /// <summary>
        /// Initializes a new instance of the BTOpenErrHandler class, wit empty constructor
        /// </summary>
        public BTOpenEventHandler() {}

        #endregion

        #region Public methods

        /// <summary>
        /// Get OpenMessage
        /// </summary>
        /// <param name="theFrame">Frame to Convert</param>
        /// <returns>a BTOpenMessage</returns>
        public BTOpenMessage GetOpenMessage(string theFrame)
        {
            //Build Open Message
            BTOpenMessage openMsg = opa.FromFrameToMsg(theFrame);

            return openMsg;
        }

        /// <summary>
        /// Handle Event
        /// </summary>
        /// <param name="theMsg">Low Level Message</param>
        /// <param name="targetMsg">High Level Message</param>
        public void HandleEvent(BTOpenMessage theMsg, object targetMsg)
        {
            //Conversion Phase: from low-level to high-level
            conv.ConvertToHighMsg(theMsg, targetMsg);
        }

        /// <summary>
        /// Dissect BTicino OPEN frame and it creates a high level language message, defined by user
        /// </summary>
        /// <param name="typDic">Type of BTicino frame</param>
        /// <param name="theFrame">BTicino OPEN frame</param>
        /// <returns>High level language message</returns>
        public object DissectFrame(Dictionary<string, Type> typDic, string theFrame)
        {
            object targetInstance = null;

            BTOpenMessage openMsg = opa.FromFrameToMsg(theFrame);
            Type targetMsg = typDic[openMsg.MsgType];

            ConstructorInfo ctor = targetMsg.GetConstructor(System.Type.EmptyTypes);
            if (ctor != null)
            {
                targetInstance = ctor.Invoke(null);

            }
            else
            {
                // Unable to convert a frome to an object
                logger.Error("Ubale to convert frame to Object fo frame : "+theFrame);
            }

            conv.ConvertToHighMsg(openMsg, targetInstance);

            return(targetInstance);
        }


        /// <summary>
        /// Dissect BTicino OPEN frames and it creates some high level language messages, defined by user
        /// </summary>
        /// <param name="typDic">Type of BTicino frames</param>
        /// <param name="theFrame">BTicino OPEN frames</param>
        /// <returns>High level language messages</returns>
        public List<object> DissectFrames(Dictionary<string, Type> typDic, string theFrames, char theSep)    {

            List<object> theRetValues = new List<object>(0);

            string[] framesList = theFrames.Split(new char [] {theSep}, StringSplitOptions.RemoveEmptyEntries);
            
            object curValue=null;

            foreach (string curFrame in framesList)    {
                
                if(curFrame.Equals(BTOpenConstFrame.ACK_FRM) || curFrame.Equals(BTOpenConstFrame.NACK_FRM))
                    continue;

                curValue = DissectFrame(typDic, curFrame);
                
                if(curValue != null)
                    theRetValues.Add(curValue);    

            }

            return (theRetValues);
        }

        #endregion
    }
}
